import { Request, Response, NextFunction } from "express";
import { connection } from "@/services/database";
import { generateUpdateFields, checkIsStudentBelongUser, checkIsAdmin } from "@/utils/sql";

interface Params {
	user_id: number;
	school_code: string;
}
export default async (request: Request, response: Response, next: NextFunction) => {
	try {
		const callerId = response.locals.user.id;
		const params = request.body as unknown as Params;
		if (callerId != params.user_id && !(await checkIsStudentBelongUser(callerId, params.user_id)) && !(await checkIsAdmin(callerId))) throw new Error("无权操作");
		const [countResults] = (await connection.execute("SELECT COUNT(*) AS count FROM school WHERE school_code = :school_code", params)) as any;
		if (countResults[0]?.count < 1) throw new Error("学校不存在");
		const [results] = (await connection.execute("SELECT school_code FROM student WHERE user_id = :user_id", params)) as any;
		if (!results[0]) throw new Error("未查询到学生");
		if (results[0].school_code !== null) throw new Error("不可重复绑定学校");
		(await connection.execute("UPDATE student SET " + generateUpdateFields({ school_code: params.school_code }) + " WHERE user_id = :user_id", params)) as any;
		response.json({ data: null, message: "成功" });
	} catch (error) {
		response.statusCode = 400;
		next(error);
	}
};
